﻿namespace BEGDC.CC.Web.EZVisit.Controls
{
    #region Using Directives

    using System;
    using System.Data;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using ASBCC.Workflow.K2Manager;
    using BL.Common;
    using ExcelTool;
    using UserControls;
    using Utility.Extensions;

    #endregion

    public partial class EZVRequestCustomer : EZVRequestBaseControl
    {
        protected override void SetVisibility()
        {
            base.SetVisibility();

            // Set action column;
            this.dgCustomersList.Columns[8].Visible = this.Editable;

            this.secCustomer1.Visible = this.Editable ? this.edt_HasRfp.SelectedValue.Equals("1") : this.vw_HasRfp.Text.Equals("Yes");
            this.secCustomer2.Visible = this.Editable ? this.edt_HaveIssues.SelectedValue.Equals("1") : this.vw_HaveIssues.Text.Equals("Yes");
            this.secCustomer3.Visible = this.Editable ? this.edt_KeyMessages.SelectedValue.Equals("1") : this.vw_KeyMessages.Text.Equals("Yes");
        }

        protected override void SetViewData()
        {
            if (this.EZVisitApplication == null)
            {
                return;
            }

            if (this.Editable)
            {
                this.edt_CustomerName.Text = this.EZVisitApplication.Company;
                this.edt_CustomerCountry.Text = this.EZVisitApplication.Country.IsNotNullOrWhiteSpace() ? this.EZVisitApplication.Country : "China";
                this.edt_VisitObjectives.Text = this.EZVisitApplication.VisitObjective;
                this.edt_PotentialRevenue.Text = this.EZVisitApplication.RevenuePotential != null ? this.EZVisitApplication.RevenuePotential.Value.ToString() : string.Empty;
                this.edt_FcpaCustomer.SelectedValue = this.EZVisitApplication.IsFCPA == null || this.EZVisitApplication.IsFCPA.Value ? "1" : "0";
                this.edt_HasRfp.SelectedValue = this.EZVisitApplication.IsInRFP != null && this.EZVisitApplication.IsInRFP.Value ? "1" : "0";
                this.edt_HaveIssues.SelectedValue = this.EZVisitApplication.IsSensitiveIssue != null && this.EZVisitApplication.IsSensitiveIssue.Value ? "1" : "0";
                this.edt_KeyMessages.SelectedValue = this.EZVisitApplication.IsKeyMessage != null && this.EZVisitApplication.IsKeyMessage.Value ? "1" : "0";
                this.edt_RfpDetail.Text = this.EZVisitApplication.RFPDetail;
                this.edt_HotIssue.Text = this.EZVisitApplication.IsThereSensitiveIssue;
                this.edt_KeyMessage.Text = this.EZVisitApplication.IsThereKeyMessage;
                this.edt_CompanyProfile.Text = this.EZVisitApplication.CompanyProfile;
            }
            else
            {
                this.vw_CustomerName.Text = this.EZVisitApplication.Company;
                this.vw_CustomerCountry.Text = this.EZVisitApplication.Country;
                this.vw_VisitObjectives.Text = this.EZVisitApplication.VisitObjective;
                this.vw_PotentialRevenue.Text = this.EZVisitApplication.RevenuePotential != null ? this.EZVisitApplication.RevenuePotential.Value.ToString() : string.Empty;
                this.vw_FcpaCustomer.Text = this.EZVisitApplication.IsFCPA == null || this.EZVisitApplication.IsFCPA.Value ? "Yes" : "No";
                this.vw_HasRfp.Text = this.EZVisitApplication.IsInRFP != null && this.EZVisitApplication.IsInRFP.Value ? "Yes" : "No";
                this.vw_HaveIssues.Text = this.EZVisitApplication.IsSensitiveIssue != null && this.EZVisitApplication.IsSensitiveIssue.Value ? "Yes" : "No";
                this.vw_KeyMessages.Text = this.EZVisitApplication.IsKeyMessage != null && this.EZVisitApplication.IsKeyMessage.Value ? "Yes" : "No";
                this.vw_RfpDetail.Text = this.EZVisitApplication.RFPDetail;
                this.vw_HotIssue.Text = this.EZVisitApplication.IsThereSensitiveIssue;
                this.vw_KeyMessage.Text = this.EZVisitApplication.IsThereKeyMessage;
                this.vw_CompanyProfile.Text = this.EZVisitApplication.CompanyProfile;
            }

            this.BindRevenueFrameDropDownList();
            this.BindAccountTypesDropDownList();
            this.BindSalesStageDropDownList();
            this.BindCustomers();
        }

        /// <summary>
        /// Binds the customers. Also called by the postback.
        /// </summary>
        public void BindCustomers()
        {
            if (this.EZVisitApplication == null || !this.Visible)
            {
                return;
            }

            var dt = this.Session[Common.EZVRequestCustomer.SessionKey + this.SessionKey] as DataTable;

            if (dt == null)
            {
                this.Session[Common.EZVRequestCustomer.SessionKey + this.SessionKey] = dt = SetRowID(this.BuildCustomerTable());
            }

            DataView dv = dt.DefaultView;

            dv.RowFilter = "IsEnabled=1";

            this.dgCustomersList.DataSource = dv;
            this.dgCustomersList.DataBind();
            this.lblTotalGuests.Text = dv.Count.ToString();
        }

        protected override bool Validate(out string error)
        {
            error = string.Empty;

            if (this.CurrentActionType.IsNotNullOrWhiteSpace() && this.dgCustomersList.Items.Count == 0)
            {
                error = @"- [Customer Info.] Customers list were not provided.\n";
            }

            return error.Length == 0;
        }

        public override void Save(EZVisitApplicationTableEntity app)
        {
            if (app == null)
            {
                return;
            }

            app.Company = this.edt_CustomerName.Text;
            app.Country = this.edt_CustomerCountry.Text;
            app.IsFCPA = this.edt_FcpaCustomer.SelectedValue.Equals("1");
            app.NumberOfPerson = this.dgCustomersList.Items.Count.ToString();
            app.VisitObjective = this.edt_VisitObjectives.Text;
            app.RevenuePotential =  new decimal();

            if (this.edt_PotentialRevenue.Text.IsNotNullOrWhiteSpace())
            {
                decimal revenue;

                if (decimal.TryParse(this.edt_PotentialRevenue.Text, out revenue))
                {
                    app.RevenuePotential = revenue;
                }
            }

            app.PotentialRevenueTimeframe = Convert.ToInt32(this.edt_RevenueTimeFrame.SelectedValue);
            app.PotentialRevenueTimeframeText = this.edt_RevenueTimeFrame.SelectedItem.Text;
            app.SalesStage = Convert.ToInt32(this.edt_SalesStage.SelectedValue);
            app.SalesStageText = this.edt_SalesStage.SelectedItem.Text;
            app.IsInRFP = this.edt_HasRfp.SelectedValue.Equals("1");
            app.RFPDetail = app.IsInRFP.Value ? this.edt_RfpDetail.Text : string.Empty;
            app.IsSensitiveIssue = this.edt_HaveIssues.SelectedValue.Equals("1");
            app.IsThereSensitiveIssue = app.IsSensitiveIssue.Value ? this.edt_HotIssue.Text : string.Empty;
            app.IsKeyMessage = this.edt_KeyMessages.SelectedValue.Equals("1");
            app.IsThereKeyMessage = app.IsKeyMessage.Value ? this.edt_KeyMessage.Text : string.Empty;
            app.CompanyProfile = this.edt_CompanyProfile.Text;
            app.AccountType = Convert.ToInt32(this.edt_AccountTypes.SelectedValue);
            app.AccountTypeText = this.edt_AccountTypes.SelectedItem.Text;

            base.Save(app);
            this.SaveCustomers();
        }

        private void SaveCustomers()
        {
            var dt = this.Session[Common.EZVRequestCustomer.SessionKey + this.SessionKey] as DataTable;

            if (dt == null || dt.Rows.Count == 0)
            {
                return ;
            }

            // Insert / Update contracts
            var customers = dt.ToEntities<EZVisitCustomerAttendeeTableEntity>();

            foreach (EZVisitCustomerAttendeeTableEntity customer in customers)
            {
                customer.AppID = this.EZVisitApplication.AppID;

                if (customer.AttendeeIDIsNull())
                {
                    EZVisitCustomerAttendeeManager.Insert(customer);
                }
                else
                {
                    EZVisitCustomerAttendeeManager.Update(customer);
                }
            }

            this.Session[Common.EZVRequestCustomer.SessionKey + this.SessionKey] = SetRowID(this.BuildCustomerTable());
            this.BindCustomers();
        }

        private void BindRevenueFrameDropDownList()
        {
            WebUtility.BuildDropDown(this.edt_RevenueTimeFrame, DicType.POTENTIAL_REVENUE_TIMEFRAME, false, false);

            if (this.EZVisitApplication.PotentialRevenueTimeframe != null)
            {
                this.edt_RevenueTimeFrame.SelectedValue = this.EZVisitApplication.PotentialRevenueTimeframe.Value.ToString();
                this.vw_RevenueTimeFrame.Text = this.edt_RevenueTimeFrame.SelectedItem.Text;
            }
        }

        private void BindSalesStageDropDownList()
        {
            WebUtility.BuildDropDown(this.edt_SalesStage, DicType.SALES_STAGE, false, false);
            if (this.EZVisitApplication.SalesStage != null)
            {
                this.edt_SalesStage.SelectedValue = this.EZVisitApplication.SalesStage.Value.ToString();
                this.vw_SalesStage.Text = this.edt_SalesStage.SelectedItem.Text;
            }
        }

        private void BindAccountTypesDropDownList()
        {
            WebUtility.BuildDropDown(this.edt_AccountTypes, DicType.ACCOUNT_TYPE, false, false);
            if (this.EZVisitApplication.AccountType != null)
            {
                this.edt_AccountTypes.SelectedValue = this.EZVisitApplication.AccountType.Value.ToString();
                this.vw_AccountTypes.Text = this.edt_AccountTypes.SelectedItem.Text;
            }
        }

        private DataTable BuildCustomerTable()
        {
            var dt = QueryExtensions.CreateDataTableSchemaFromEntity(typeof(EZVisitCustomerAttendeeTableEntity));

            var appId = this.EZVisitApplication.AppID;

            if (appId != null && appId.Value > 0)
            {
                string condition = string.Format("AppID='{0}' and IsEnabled=1", appId);
                dt = EZVisitCustomerAttendeeManager.SelectByCondition(condition).OfType<EZVisitCustomerAttendeeTableEntity>().ToDataTable();
            }

            dt.Columns.Add("RowId");
            return dt;
        }

        protected void dgCustomersList_DeleteCommand(object source, DataGridCommandEventArgs e)
        {
            int rowId = Convert.ToInt32(e.Item.Cells[0].Text);

            var dt = (DataTable)this.Session[Common.EZVRequestCustomer.SessionKey + this.SessionKey];

            DataRow row = dt.Rows[rowId - 1];

            // Newly added contract?
            if (row.IsNull("AttendeeID"))
            {
                dt.Rows.Remove(row);
            }
            else
            {
                row["IsEnabled"] = false;
                row["UpdateAt"] = DateTime.Now;
                row["UpdateBy"] = this.CurrentUser;
            }

            this.Session[Common.EZVRequestCustomer.SessionKey + this.SessionKey] = SetRowID(dt);

            this.BindCustomers();
        }

        protected void dgCustomersList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType != ListItemType.Item) && (e.Item.ItemType != ListItemType.AlternatingItem))
            {
                return;
            }

            var cell = e.Item.Cells[8];

            var btnEdit = (ImageButton)cell.FindControl("btnEdit");
            btnEdit.Attributes.Add("onclick", "return openCustomerPanel('" + e.Item.Cells[0].Text + "');");

            var btnDelete = (ImageButton)cell.FindControl("btnDelete");
            btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
        }

        private static DataTable SetRowID(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 1; i <= table.Rows.Count; i++)
                {
                    table.Rows[i - 1]["RowId"] = i.ToString();
                }
            }
            return table;
        }

        protected void edt_HasRfp_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.secCustomer1.Visible = this.edt_HasRfp.SelectedValue.Equals("1");
        }

        protected void edt_HaveIssues_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.secCustomer2.Visible = this.edt_HaveIssues.SelectedValue.Equals("1");
        }

        protected void edt_KeyMessages_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.secCustomer3.Visible = this.edt_KeyMessages.SelectedValue.Equals("1");
        }

        protected void btnExportCustomers_Click(object sender, EventArgs e)
        {
            if (this.EZVisitApplication == null)
            {
                return;
            }

            this.CurrentActionType = K2ActionType.Save;
            this.Save(this.EZVisitApplication);

            new ExportCustomers().Export(this.Page, this.EZVisitApplication.AppID.Value);
        }
    }
}